<include file="header"/>
<include file="commonJs"/>
<div class="wraper">
    <div class="none">
    </div>
</div>
<script id="entry-tpl" type="text/x-handlebars-template">
    <div class="operate">
        <p class="operate-theme pull-left">购物车（<span>{{pageData.length}}</span>）</p>
        <a href="javascript:;" class="operate-delete pull-left">删除</a>
        <a href="javascript:;" class="operate-collect pull-left">加入收藏夹</a>
    </div>
    {{#each pageData}}
    <div class="cart-list clearfix">
        <div class="list-info check-item-{{cart_id}}" data-id="{{cart_id}}">
            <div class="checkbox">
                <span class="iconfont icon-checkbox"></span>
            </div>
            <div class="product-img"><img src="{{goods_image}}"/></div>
            <div class="product-info">
                <p>{{goods_name}}</p>
                {{#if specification}}
                <p class="specification">规格：{{specification}}</p>
                {{/if}}
            </div>
        </div>
        <div class="cart-detail checkbox clearfix">
            <span class="new-prize">￥{{goods_price}}</span>
            <if condition="session('wechat_id') neq 22">
			<span class="old-prize"><del>￥{{goods_original_price}}</del></span>
			</if>

            <div class="quantity pull-right">
                    <span class="iconfont icon-iconfont55 change-num-btn  sub-btn-{{cart_id}}" data-id="{{cart_id}}"
                          data-status="sub"></span>
                <input type="number" value="{{goods_num}}" class="buy-count buy-count-{{cart_id}}"
                       data-id="{{cart_id}}" data-status="input"/>
                    <span class="iconfont icon-jia change-num-btn plus-btn-{{cart_id}}" data-id="{{cart_id}}"
                          data-status="plus"></span>
            </div>
        </div>
    </div>
    {{/each}}
    <div class="amount">已选 <span class="amount-num">0</span> 件商品</div>
	
    <div class="fixed-accounts ">
    <div class="tb-mode">
		<div class="checkbox tb-cell describ-gray checked-all">
            <span class="iconfont icon-checkbox"></span>
            <span>全选</span>
        </div>
        <div class="total tb-celll">
            <p class="text-right">合计：<span class="describ-red" id="cost-total">0.00</span></p>

            <p class="describ-gray text-right">不含运费</p>
        </div>
        <div class="amount-btn tb-cell">
            <a class="describ-white btn" href="javascript:;">结算（<span class="amount-num">0</span>）</a>
        </div>
    </div>
    </div>
</script>
<script>
    $(function () {
//        Handlebars.registerHelper("totalPrice", function(items) {
//            var total = 0;
//            items.forEach(function (v, i) {
//                total += Number(v.goods_price) * Number(v.goods_num);
//            });
//            return total.toFixed(2);
//        });

        var pageSource = $('#entry-tpl').html();
        var pageTpl = Handlebars.compile(pageSource);
        var storeId="{BEESCRM:$storeId}";
		var url='/base/store/getCart';
		if(storeId){
			url+='/store_id/'+storeId;
		}
        $.getAjax({
            url: url,
            method: 'GET',
            data: {}
        }, false, function (res) {
            var data = res,
                    pageData,
                    checkedList = {},
                    isChecked = false;
            if (data.status ='S') {
                if(data.data){
                    pageData = data.data || [];
                    var elem = $('.wraper');
                    elem.html(pageTpl({pageData: pageData}));
                }
                else{
                    var str = '';
                    str += '<span class="iconfont icon-tanhao tanhao"></span><p class="text-color">购物车空虚寂寞冷</p><p>快点挑点宝贝吧</p>'+
                    '<div class="retail-btn"> <a href="{BEESCRM::U('base/storeOld/userindex',array('store_id'=>$storeId,'origin'=>$origin))}">个人中心</a>'+
                    '<a href="{BEESCRM::U('base/storeOld/index',array('store_id'=>$storeId,'origin'=>$origin))}">去逛逛</a> </div>';
                    $('.none').html(str);
                }

//                单选
                elem.on('click', '.list-info', function () {
                    var id = $(this).data('id');

                    var checkedData = pageData.filter(function (v, i) {
                        return v.cart_id == id;
                    });

                    if (checkedList[id]) {
                        delete checkedList[id];
                    } else {
                        checkedList[id] = checkedData[0];
                    }

                    if (pageData.length === Object.keys(checkedList).length) {
                        renderData(checkedList, true);
                    } else {
                        renderData(checkedList);
                    }
                    renderTotalCost(checkedList);
                });
//  全选
                elem.on('click', '.checked-all', function () {
                    if (pageData.length === Object.keys(checkedList).length) {
                        checkedList = {};
                    } else {
                        $.each(pageData, function (i, v) {
                            checkedList[v.cart_id] = v;
                        });
                    }
                    renderTotalCost(checkedList);
                    renderData(checkedList, true);
                });

//                数量增减
                elem.on('click', '.change-num-btn', function () {
                    var id = $(this).data('id'),
                            status = $(this).data('status');
                    renderNumVal(id, status);
                });
//输入数量
                elem.on('change', '.buy-count', function () {
                    var id = $(this).data('id'),
                            status = $(this).data('status');
                    renderNumVal(id, status);
                });

//                收藏
                elem.on('click', '.operate-collect', function () {
                    if (Object.keys(checkedList).length <= 0) {
                        $.alert('error', '未选中商品');
                        return false;
                    }

                    $.getAjax({
                        url: '/base/storeOld/movetocollection/store_id/{BEESCRM:$storeId}',
                        method: 'POST',
                        data: {cart_id: Object.keys(checkedList)}
                    }, true);

                });

//                删除
                elem.on('click', '.operate-delete', function () {
                    if (Object.keys(checkedList).length <= 0) {
                        $.alert('error','您未选择删除的商品');
                        return false;
                    }

                    $.getAjax({
                        url: '/base/storeOld/deletefromcart/store_id/{BEESCRM:$storeId}',
                        method: 'POST',
                        data: {cart_id: Object.keys(checkedList)}
                    }, false, function (res) {
                        var data = res;
                        if (data.status === 'S') {
                            pageData = data.data;
                            elem.html(pageTpl({pageData: pageData}));
                        } else {
                            alert('error', data.message);
                        }
                    });

                });

//                结算
                elem.on('click', '.amount-btn', function () {

                    if(Object.keys(checkedList).length <= 0) {
                        $.alert('error','您还未选择商品');
                        return false;
                    }
                    var submitData = [],
                            pdData = {};
                    $.each(checkedList, function (k, v) {
                        pdData = {
                            cart_id: k,
                            goods_num: v.goods_num,
                            goods_price: v.goods_price
                        };
                        submitData.push(pdData);
                    });

                    $.getAjax({
                        url: '/base/storeOld/createorder/store_id/'+storeId,
                        method: 'POST',
                        data: {cart: submitData, order_amount: $('#cost-total').text() }
                    }, true,redirect);
                });
				
				function redirect(data){
					location=data.url;
				}
				
                function renderNumVal(id, status) {
                    var initNum;

                    var numData = pageData.filter(function (v, i) {
                        return v.cart_id == id;
                    });

                    initNum = parseInt(numData[0].goods_num);

                    if (status == 'plus') {
                        initNum++;
                    } else if (status == 'sub') {
                        if (initNum <= 1) {
                            initNum = 1;
                            return false;
                        }
                        initNum--;
                    } else if (status == 'input') {
                        initNum = $('.buy-count-' + id + '').val();
                        if (initNum <= 1) {
                            initNum = 1;
                            $('.buy-count-' + id + '').val(initNum);
                        }
                    }

                    pageData.map(function (v, i) {
                        if (v.cart_id == id) {
                            return v.goods_num = initNum;
                        }
                    });

                    renderTotalCost(checkedList);

                    $('.buy-count-' + id + '').val(initNum);

                    $.get('/base/storeOld/updatecartnum/store_id/{BEESCRM:$storeId}', {
                        cart_id: id,
                        goods_num: initNum
                    });
                }
            }
        });

        function renderData(data, checkAll) {
            $('.icon-checkbox').removeClass('icon-xuanzedianjihou');
            $.each(data, function (i, v) {
                $('.check-item-' + i + '').find('.icon-checkbox').addClass('icon-xuanzedianjihou');
            });
            $('.amount-num').text(Object.keys(data).length);

            if (checkAll) {
                $('.fixed-accounts').find('.icon-checkbox').addClass('icon-xuanzedianjihou');
            }
            if (Object.keys(data).length === 0) {
                $('.fixed-accounts').find('.icon-checkbox').removeClass('icon-xuanzedianjihou');
            }
        }

        function renderTotalCost(data) {
            var total = 0;
            $.each(data, function (i, v) {
                total += Number(v.goods_price) * Number(v.goods_num);
            });
            $('#cost-total').text(total.toFixed(2));
        }
    });
</script>
<include file="footer"/>